/**
 * Created by Ysssssss on 2021/4/21.
 */

import React, { PureComponent } from 'react'
import {connect} from "react-redux";
import dayjs from "dayjs";
import {Select, Tabs, Button} from 'antd'
import {withRouter} from "react-router-dom";
import { getShoppingMallOrderList } from "@sagas/shoppingMall/shoppingMallOrder";
import {getQuery, handleQueryEqual, setQuery} from "@utils/setUrlQuery";
import CustomizeTableProvide, {
    CustomizeOrderTable,
    CustomizeTablePagination
} from "@common/presentational/CustomizeTable";
import {
    SHOPPING_MALL_ORDER_STATUS, SHOPPING_MALL_ORDER_STATUS_CODE,
    SHOPPING_MALL_ORDER_STATUS_LIST,
} from "@constants/ShoppingMallOrderStatus";
import DateRangePicker from "@common/presentational/DateRangePicker";
import { AllWarehouseSelect } from '@components/warehouse/AllWarehouseSelect'
import ParamsInput from "@common/presentational/ParamsInput";
import ShoppingMallRefundReasonModal from "@components/shoppingMall/modal/ShoppingMallRefundReasonModal";
import {priceFenToYuan} from "@utils/priceConversion";

@connect(({ shoppingMallOrder }) => ({
    orderListMap: shoppingMallOrder.orderListMap
}), {
    getShoppingMallOrderList
})
@withRouter
class ShoppingMallOrderPage extends PureComponent {
    constructor(props) {
        super(props);
        const {
            startDate = dayjs().subtract(3, 'month').format('YYYY-MM-DD'),
            endDate = dayjs().format('YYYY-MM-DD'),
            creator = '',
            warehouseId = '',
            status = '',
            orderNo = '',
        } = getQuery(props.history)
        this.state = {
            startDate,
            endDate,
            creator,
            warehouseId,
            status,
            orderNo,
        }

        this.tableRef = React.createRef()
        this.shoppingMallRefundReasonModal = React.createRef()
        this.getTableInfo = this.getTableInfo.bind(this)

        this.paginationInfo = {}
        this.columns = [{
            dataIndex: 'creator',
            key: 'creator',
            width: '10%',
            render: text => text.includes('/') ? (
                <>
                    <div className="text-center">
                        {text.split('/')[0]}
                    </div>
                    <div className="text-center">
                        {text.split('/')[1]}
                    </div>
                </>
            ) : (text || '--')
        }, {
            dataIndex: 'status',
            key: 'status',
            width: '10%',
            render: (text, record) => {
                let statusStr = SHOPPING_MALL_ORDER_STATUS[text] || '--'
                if (record.storage_status) {
                    return (
                        <>
                            <div className="text-center">{ statusStr }</div>
                            <div className="text-center clr-orange">(部分商品库存不足)</div>
                        </>
                    )
                }
                return statusStr
            }
        }, {
            dataIndex: 'trans',
            key: 'trans',
            width: '10%',
            render: text => `￥${priceFenToYuan(text)}`
        }, {
            dataIndex: 'status',
            key: 'operation',
            width: '120px',
            render: (text, record) => this.renderListOperation(record)
        }]
        this.titleLineRender = data => (
            <>
                <span>订单编号：{data.order_number}</span>
                <span>下单时间：{data.submit_time}</span>
            </>
        )

    }

    handleValueChange (key, value) {
        if (key === 'dateRange') {
            this.setState({
                ...value
            }, this.initTable)
            return;
        }
        if (key === 'status') {
            this.setState({
                [key]: value === '' ? '' : parseInt(value)
            }, this.initTable)
            return;
        }
        this.setState({
            [key]: value
        }, this.initTable)
    }

    goOrderDetail = ({ order_number }) => {
        const { history } = this.props
        history.push(`/shopping-mall/order/${order_number}/detail`)
    }

    goOrderAfterSalesOrderPage = (orderNumber) => {
        const { history } = this.props
        history.push(`/shopping-mall/after-sales?orderNo=${orderNumber}`)
    }

    renderListOperation = (record) => {
        if (record.refund_flag) {
            return (
                <div className="flex-row-right">
                    <Button type="primary" ghost className="button-in-table mgr-24" onClick={this.goOrderAfterSalesOrderPage.bind(this, record.order_number)}>查看退款</Button>
                    <a className="row-modify-button" onClick={this.goOrderDetail.bind(this,record)}>详情</a>
                </div>
            )
        }
        switch(record.status) {
            case SHOPPING_MALL_ORDER_STATUS_CODE.prepare_products:
                return (
                    <div className="flex-row-right">
                        <Button type="primary" ghost className="button-in-table mgr-24" onClick={this.cancelOrder.bind(this,record.order_number)}>取消订单</Button>
                        <a className="row-modify-button" onClick={this.goOrderDetail.bind(this,record)}>详情</a>
                    </div>
                )
            default:
                return (
                    <div className="flex-row-right">
                        <a className="row-modify-button" onClick={this.goOrderDetail.bind(this,record)}>详情</a>
                    </div>
                )
        }
    }

    getTableInfo ({ current, pageSize } = this.paginationInfo) {
        this.paginationInfo = { current, pageSize }
        const { startDate, endDate, status, orderNo, creator, warehouseId } = this.state
        this.props.getShoppingMallOrderList({
            startDate,
            endDate,
            status,
            keywordOrderNo: orderNo,
            creator,
            warehouseId,
            pageNo: current,
            pageSize,
        })
        this.setUrlQuery()
    }

    initTable () {
        this.tableRef.current?.initPage()
    }

    cancelOrder (orderNumber) {
        this.shoppingMallRefundReasonModal.current?.show({ orderNumber })
    }

    setUrlQuery () {
        const { current, pageSize } = this.paginationInfo
        const { startDate, endDate, status, orderNo, creator, warehouseId } = this.state
        const { history } = this.props
        let params = {
            startDate, endDate, status, orderNo, creator, warehouseId, current, pageSize
        }
        handleQueryEqual(params, history) || setQuery(params, history)
    }

    render () {
        const { orderListMap } = this.props
        const { startDate, endDate, creator, warehouseId, status, orderNo } = this.state
        return (
            <div className="table-scroll-container shopping-mall-page shopping-mall-order-list-page">
                <div className="table-params page-params flex-vertical-center mgb-16">
                    <AllWarehouseSelect
                        showAll
                        value={warehouseId}
                        onChange={this.handleValueChange.bind(this, 'warehouseId')}
                    />
                    <DateRangePicker
                        className="mgl-16"
                        startDate={startDate}
                        endDate={endDate}
                        onChange={this.handleValueChange.bind(this, 'dateRange')}
                        beforeNow
                    />
                    <ParamsInput
                        className="mgl-16"
                        style={{width: '140px'}}
                        value={creator}
                        onChange={this.handleValueChange.bind(this, 'creator')}
                        placeholder="下单人/手机号"
                    />
                    <ParamsInput
                        className="mgl-16"
                        style={{width: '140px'}}
                        value={orderNo}
                        onChange={this.handleValueChange.bind(this, 'orderNo')}
                        placeholder="订单编号"
                    />
                    <Tabs className="mgt-8 w-100"
                          activeKey={`${status}`}
                          onChange={this.handleValueChange.bind(this, 'status')}
                    >
                        { SHOPPING_MALL_ORDER_STATUS_LIST.filter(orderStatus => !orderStatus.notSearch).map(orderStatus => (
                            <Tabs.TabPane tab={orderStatus.name} key={`${orderStatus.id}`}/>
                        )) }
                    </Tabs>
                </div>
                <CustomizeTableProvide ref={this.tableRef} tableKey="shoppingMallOrderList" onChange={this.getTableInfo}>
                    <div className="table-list">
                        <CustomizeOrderTable
                            columns={this.columns}
                            dataSource={orderListMap.orders || []}
                            pagination
                            titleLineRender={this.titleLineRender}
                        />
                    </div>
                    <div className="table-pagination">
                        <CustomizeTablePagination
                            total={orderListMap.total}
                        />
                    </div>
                </CustomizeTableProvide>
                <ShoppingMallRefundReasonModal
                    ref={this.shoppingMallRefundReasonModal}
                    callback={this.getTableInfo}
                />
            </div>
        )
    }
}

export default ShoppingMallOrderPage